package edu.uni.dormitory.controller;

import edu.uni.auth.bean.User;
import edu.uni.auth.service.AuthService;
import edu.uni.bean.Result;
import edu.uni.dormitory.bean.AccomodateApply;
import edu.uni.dormitory.globalbean.AccommodateVo;
import edu.uni.dormitory.globalbean.StudentBedVo;
import edu.uni.dormitory.service.AccommodateService;
import edu.uni.dormitory.service.StudentBedService;
import edu.uni.example.config.ExampleConfig;
import edu.uni.userBaseInfo1.bean.Employee;
import edu.uni.userBaseInfo1.bean.StudentRelation;
import edu.uni.userBaseInfo1.service.EmployeeService;
import edu.uni.userBaseInfo1.service.StudentRelationService;
import edu.uni.userBaseInfo1.service.StudentService;
import edu.uni.userBaseInfo1.service.UserService;
import edu.uni.dormitory.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;

import static edu.uni.bean.ResultType.Failed;
import static edu.uni.bean.ResultType.Success;

/**
 * @author 郑伟森
 * @create 2019.05.01
 * @function 假期留宿
 */
@Api(description = "假期留宿模块")
@RestController
@RequestMapping("json/dorm/accommodate")
public class AccommodateController{
    @Autowired
    private AccommodateService accommodateService;
    @Autowired
    private ExampleConfig globalConfig;

    @Autowired
    private StudentService studentService;
    @Autowired
    private UserService userService;
    @Autowired
    private StudentRelationService studentRelationService;
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private StudentBedService studentBedService;


    @Autowired
    private AuthService authService;
    /**
     * 通过主键获取某条留宿记录
     */
    @ApiOperation(value = "通过主键获取某条留宿记录", notes = "")
    @GetMapping("{id}")
    public Result receiveAccommodateById(@PathVariable("id")Long id, HttpSession session){
        User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能获取的权限
        AccomodateApply accomodateApply=null;
        //学生
        if(isHasRole(roleList,"学生")){
            accomodateApply = accommodateService.selectAccommodateApplyById(id, Long.valueOf(loginId));

        }//家长
        else if(isHasRole(roleList,"家长")){
//                最好是有缓存是谁的家长
            Long childId = (Long) session.getAttribute("childId");
            if(childId == null){
                StudentRelation studentRelation = studentRelationService.selectRelaByRelaId(Long.valueOf(loginId));
                childId = studentRelation.getUserId();
            }
            accomodateApply = accommodateService.selectAccommodateApplyById(id, childId);
        }//辅导员
        else if(isHasRole(roleList,"辅导员")){
//                最好是有缓存是哪个学院的辅导员
            Long collegeId = (Long) session.getAttribute("collegeId");
            if(collegeId == null){
                long employeeId = getEmploeeIdByUserId(Long.valueOf(loginId));
                if(employeeId == -1) Result.build(Failed);
                collegeId = employeeService.selectEmployeeById(employeeId).getDepartmentId();
            }
            accomodateApply = accommodateService.selectAccommodateApplyByIdWithInstructor(id, collegeId);
        }//宿管中心
        else if(isHasRole(roleList,"宿管中心")){
            accomodateApply = accommodateService.selectAccommodateApplyByIdWithSettlementCenter(id);
        }
        if(accomodateApply != null){
            String applyId = String.valueOf(accomodateApply.getId());
            String studentNo = studentService.selectById(accomodateApply.getApplyPerson()).getStuNo();
            String studentName = userService.selectUserById(accomodateApply.getByWho()).getUserName();
            String applyTime = DateUtil.date2string(accomodateApply.getApplyDate());
            String begin =  DateUtil.date2string(accomodateApply.getBegin());
            String end =  DateUtil.date2string(accomodateApply.getEnd());
            String reason = accomodateApply.getReason();
            String status = accommodateService.selectAccommodateStatusByApplyId(accomodateApply.getId());
            StudentBedVo studentBedVo = studentBedService.selectStudentBedBySid(Long.parseLong(loginId));
            String areaName = studentBedVo.getAreaName();
            String room = String.valueOf(studentBedVo.getRoom());
            AccommodateVo accommodateVo = new AccommodateVo(applyId,studentName,studentNo,applyTime,begin,end,reason,areaName,room,status);
            return Result.build(Success).appendData("list",new ArrayList<AccommodateVo>(){{this.add(accommodateVo);}});
        }
        //缓存
        return Result.build(Failed);
    }


    /**
     * 获取留宿记录
     */
    @ApiOperation(value = "获取所有留宿记录", notes = "")
    @GetMapping("listAll")
    public Result listAccommodate(String areaId,HttpSession session,Integer status){
        User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能获取的权限
            List<AccomodateApply> accomodateApplyList=null;
            //学生
            if(isHasRole(roleList,"学生")){
                accomodateApplyList = accommodateService.selectAccommodateApplyPageBySelf(Long.valueOf(loginId));
            }//家长
            else if(isHasRole(roleList,"家长")){
                //最好是有缓存是谁的家长
                Long childId = (Long) session.getAttribute("childId");
                if(childId == null){
                    StudentRelation studentRelation = studentRelationService.selectRelaByRelaId(Long.valueOf(loginId));
                    childId = studentRelation.getUserId();
                }
                accomodateApplyList = accommodateService.selectAccommodateApplyPageByChild(childId);
            }//辅导员
            else if(isHasRole(roleList,"辅导员")){
                //最好是有缓存是哪个学院的辅导员
                Long collegeId = (Long) session.getAttribute("collegeId");
                if(collegeId == null){
                    long employeeId =getEmploeeIdByUserId(Long.valueOf(loginId));
                    if(employeeId == -1) Result.build(Failed);
                    collegeId = employeeService.selectEmployeeById(employeeId).getDepartmentId();
                }
                accomodateApplyList = accommodateService.selectAccommodateApplyPageByCollege(collegeId);
            }//宿管中心
            else if(isHasRole(roleList,"宿管中心人员")){
                accomodateApplyList = accommodateService.selectAccommodateApplyList();
//                accomodateApplyList = accommodateService.selectAccommodateApplyPageByArea(areaId);
            }
            if(accomodateApplyList != null && accomodateApplyList.size()>0){
                List<AccommodateVo> accommodateVoList = new ArrayList<>();
                for(AccomodateApply apply:accomodateApplyList){
                    String s = accommodateService.selectAccommodateStatusByApplyId(apply.getId());
                    if(!judgeStatus(status,s,roleList)) continue;
                    String applyId = String.valueOf(apply.getId());
                    String studentNo = studentService.selectById(apply.getApplyPerson()).getStuNo();
                    String studentName = userService.selectUserById(apply.getByWho()).getUserName();
                    String applyTime = DateUtil.date2string(apply.getApplyDate());
                    String reason = apply.getReason();
                    String begin =  DateUtil.date2string(apply.getBegin());
                    String end =  DateUtil.date2string(apply.getEnd());

                    StudentBedVo studentBedVo = studentBedService.selectStudentBedBySid(apply.getApplyPerson());
                    String areaName = studentBedVo.getAreaName();
                    String room = String.valueOf(studentBedVo.getRoom());
                    accommodateVoList.add(new AccommodateVo(applyId,studentName,studentNo,applyTime,begin,end,reason,areaName,room,s));
                }
                return Result.build(Success).appendData("list", accommodateVoList);
            }
        //缓存
        return Result.build(Failed);
    }
    /**
     * 学生申请留宿
     */
    @ApiOperation(value = "学生申请留宿", notes = "")
    @PostMapping("")
    public Result createAccommodate(@RequestBody AccomodateApply accomodateApply, HttpSession session){
        User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能申请的权限
        //学生
        if(isHasRole(roleList,"学生")){
            int i = accommodateService.insertAccommodateApply(accomodateApply,Long.valueOf(loginId));
            if(i > 0){
                return Result.build(Success);
            }
        }
        //其他人
        return Result.build(Failed);
    }
    /**
     * 审核（通过缓存的角色来判断是辅导员或家长）
     */
    @ApiOperation(value = "审核（通过缓存的角色来判断是辅导员或家长）", notes = "")
    @PostMapping("{id}")
    public Result checkAccommodate(@PathVariable("id")Integer id,String agree,HttpSession session){
        User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
//        loginId = "3";loginRole="familyHead";
//        loginId = "2106";loginRole="instructor";
        //根据身份判断是否有能申请的权限
        int i = 0;
        //辅导员
        if(isHasRole(roleList,"辅导员")){
            i = accommodateService.updateAccommodateApplyWithInstructor(Long.valueOf(id),Byte.valueOf(agree),Long.valueOf(loginId));
        }//家长
        else if(isHasRole(roleList,"家长")){
            i = accommodateService.updateAccommodateApplyWithFamilyHead(Long.valueOf(id),Byte.valueOf(agree),Long.valueOf(loginId));
        }else if(isHasRole(roleList,"宿管中心人员")){
            i = accommodateService.updateAccommodateApplyWithCenter(Long.valueOf(id),Byte.valueOf(agree),Long.valueOf(loginId));
        }
        //其他人
        if(i > 0 ){
            return Result.build(Success);
        }
        return Result.build(Failed);
    }

    private long getEmploeeIdByUserId(Long userId){
        List<Employee> employeeList = employeeService.selectByUserId(Long.valueOf(userId));
        return (employeeList==null||employeeList.size()==0)?-1:employeeList.get(0).getId();
    }

    private boolean judgeStatus(Integer status, String s, List<String> roleList){
        if(!"不同意".equals(s) && isHasRole(roleList,"家长")){
            if(0 == status && "家长确认中".equals(s)) return true;
            if(1 == status) {
                if("辅导员确认中".equals(s)||"宿管中心确认中".equals(s) || "已完成".equals(s)){
                    return true;
                }
            }
        }else if(!"不同意".equals(s) && isHasRole(roleList,"宿管中心人员")){
            if(0 == status && "宿管中心确认中".equals(s)) return true;
            if(1 == status) {
                if("已完成".equals(s)){
                    return true;
                }
            }
        }else if(!"不同意".equals(s) && isHasRole(roleList,"辅导员")){
            if(0 == status && "辅导员确认中".equals(s)) return true;
            if(1 == status) {
                if("宿管中心确认中".equals(s) || "已完成".equals(s)){
                    return true;
                }
            }
        }else if(isHasRole(roleList,"学生")){
            return true;
        }
        return false;
    }

    private boolean isHasRole(List<String> roleList, String role) {
        for(String r:roleList){
            if(r.equals(role)){
                return true;
            }
        }
        return false;
    }
}
